<template>
  <el-dialog
    :title="!dataForm.id ? '记账凭证新增' : '记账凭证修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    fullscreen
    center append-to-body>
    <el-form class="verify-form" :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
    <el-row>
      <el-col :span="8"  v-if="dataForm.id != 0">
        <el-form-item label="单号" prop="billId" >
          <el-input v-model="dataForm.billId" placeholder="单号"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="凭证日期" prop="createTime">
          <el-input v-model="dataForm.createTime" placeholder="创建时间"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="凭证人" prop="createUserName">
          <el-input v-model="dataForm.createUserName" placeholder="创建用户名称"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="8">
        <el-form-item label="附单数" prop="attachedNumber">
          <el-input v-model="dataForm.attachedNumber"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="单据种类" prop="billType">
          <el-radio-group v-model="dataForm.billType">
            <el-radio label="1">制造商</el-radio>
            <el-radio label="2">部门</el-radio>
            <el-radio label="3">客户</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="制造商" prop="typeName" v-if="dataForm.billType == '1'">
          <el-input v-model="dataForm.typeName" readonly>
            <el-button slot="append" @click="checkSupplyList">选择</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="部门" v-if="dataForm.billType == '2'">
          <el-input v-model="dataForm.typeName" readonly>
            <el-button slot="append" @click="openDeptDialog">选择</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName" v-if="dataForm.billType == '3'">
          <el-input v-model="dataForm.typeName">
            <el-button slot="append" @click="checkCustomer">选择</el-button>
          </el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item label="备注" prop="memo">
      <el-input v-model="dataForm.memo" placeholder="备注" type="textarea"></el-input>
    </el-form-item>
    </el-form>

    <!-- <el-tabs type="border-card"> -->
      <el-divider content-position="left">详细信息</el-divider>
      <el-row>
        <el-button type="primary" icon="el-icon-plus" @click.prevent="addRow()">添加科目</el-button>
        <el-button type="primary" icon="el-icon-delete" @click.prevent="delData()">删除</el-button>
      </el-row>
      <div class="avue-crud">
        <el-table :data="dataForm.detailList" border @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="direct" label="方向">
            <template slot-scope="scope">
              <el-select v-model="scope.row.direct">
                <el-option label="借" value="1"></el-option>
                <el-option label="贷" value="2"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="memo" label="摘要">
            <template slot-scope="scope">
              <el-input v-model="scope.row.memo" placeholder="摘要"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="subjectName" label="科目名称">
            <template slot-scope="scope">
              <el-input v-model="scope.row.subjectName" placeholder="科目名称" readonly>
                <el-button slot="append" @click="checkParent(scope.row)">选择</el-button>
              </el-input>
            </template>
          </el-table-column>
        
        <el-table-column prop="borrowMoney" label="借方金额">
          <template slot-scope="scope">
            <el-input v-model="scope.row.borrowMoney" placeholder="借方金额"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="loanMoney" label="贷方金额">
          <template slot-scope="scope">
            <el-input v-model="scope.row.loanMoney" placeholder="贷方金额"></el-input>
          </template>
        </el-table-column>
        </el-table>
      </div>
    <!-- </el-tabs> -->

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      <el-switch v-model="dataForm.status" active-text="保存并审核" inactive-value="0" active-value="1" style="margin-left: 15px;"></el-switch>
    </span>

    <!-- 弹窗, 制造商查询 -->
    <supply-search v-if="supplySearchVisible" ref="supplySearch" @refreshData="renewFormData"></supply-search>
    <!-- 弹窗, 部门查询 -->
    <search-dept v-if="deptVisible" ref="deptDialog" @refreshData="getDeptData"></search-dept>
    <!-- 弹窗, 选择客户 -->
    <check-customer v-if="customerVisible" ref="customer" @refreshData="customerData"></check-customer>
    <!-- 弹窗, 隶属科目查询 -->
    <parent-choose v-if="parentVisible" ref="parentDialog" @refreshData="getParentData"></parent-choose>
  </el-dialog>
</template>

<script>
    import {getObj, addObj, putObj} from '@/api/eims/evidence'
    import SupplySearch from "@/components/business/SearchSupply";
    import SearchDept from '../payslip/SearchDept'
    import { mapGetters } from "vuex";
    import CheckCustomer from "./checkCustomer";
    import ParentChoose from '../subject/parentChoose'
    export default {
    data () {
      return {
        visible: false,
        supplySearchVisible: false,
        deptVisible: false,
        customerVisible: false,
        parentVisible: false,
        dataForm: {
          id: 0,
          templateId: '',
          billId: '',
          status: '',
          evidenceType: '',
          billType: '1',
          attachedNumber: '',
          relationId: '',
          relationName: '',
          memo: '',
          createTime: '',
          updateTime: '',
          createUser: '',
          modifyUser: '',
          orgId: '',
          tenantId: '',
          unitId: '',
          delFlag: '',
          supplyName: '',
          twoType: '',
          deptName: '',
          detailList: []
        },
        dataList: [],
        customerOptions:[],
        dataRule: {
          templateId: [
            { required: true, message: '凭证模板id不能为空', trigger: 'blur' }
          ],
          billId: [
            { required: true, message: '单号不能为空', trigger: 'blur' }
          ],
          status: [
            { required: true, message: '审核状态(0-未审核,1-已审核)不能为空', trigger: 'blur' }
          ],
          evidenceType: [
            { required: true, message: '凭证类型(1-普通凭证,2-记账凭证)不能为空', trigger: 'blur' }
          ],
          billType: [
            { required: true, message: '单据种类', trigger: 'blur' }
          ],
          twoType: [
            { required: true, message: '凭证类型', trigger: 'blur' }
          ]
        }
      }
    },
    components: {
      SupplySearch,
      CheckCustomer,
      SearchDept,
      ParentChoose
    },
    computed: {
      ...mapGetters(["userInfo"])
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        if(this.dataForm.id == 0){
          this.timeFormate(new Date());
          this.dataForm.createUser = this.userInfo.id;
          this.dataForm.createUserName = this.userInfo.realName;
        }
        this.visible = true
        this.dataForm.evidenceType = 2
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            getObj(this.dataForm.id).then(response => {
              if(response.data.code == '0'){
                this.dataForm = response.data.data
                this.dataList = response.data.data.detailList
              }else{
                this.$message.error(response.data.msg)
              } 
            })
          }
        })
      },
      //显示当前时间（年月日时分秒）
      timeFormate(timeStamp) {
        let year = new Date(timeStamp).getFullYear();
        let month =
          new Date(timeStamp).getMonth() + 1 < 10 ?
          "0" + (new Date(timeStamp).getMonth() + 1) :
          new Date(timeStamp).getMonth() + 1;
        let date =
          new Date(timeStamp).getDate() < 10 ?
          "0" + new Date(timeStamp).getDate() :
          new Date(timeStamp).getDate();
        let hh =
          new Date(timeStamp).getHours() < 10 ?
          "0" + new Date(timeStamp).getHours() :
          new Date(timeStamp).getHours();
        let mm =
          new Date(timeStamp).getMinutes() < 10 ?
          "0" + new Date(timeStamp).getMinutes() :
          new Date(timeStamp).getMinutes();
        let ss =
          new Date(timeStamp).getSeconds() < 10 ?
          "0" + new Date(timeStamp).getSeconds() :
          new Date(timeStamp).getSeconds();
        this.nowTime =
          "POUT" +
          year +
          "" +
          month +
          "" +
          date +
          "" +
          hh +
          "" +
          mm +
          "" +
          ss +
          this.dataForm.deptId;
        this.dataForm.createTime = year + "-" + month + "-" + date;
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.dataForm.id) {
                putObj(this.dataForm).then(response => {
                  if(response.data.code == '0'){
                    this.$message.success('修改成功')
                    this.visible = false
                    this.$emit('refreshDataList')
                  }else{
                    this.$message.error(response.data.msg)
                  }
                });
            } else {
                this.dataForm.createTime = ''
                addObj(this.dataForm).then(response => {
                  if(response.data.code == '0'){
                    this.$message.success('添加成功')
                    this.visible = false
                    this.$emit('refreshDataList')
                  }else{
                    this.$message.error(response.data.msg)
                  }
                })
            }
          }
        })
      },
      // 选择制造商
      checkSupplyList() {
        let data = {};
        this.supplySearchVisible = true;
        this.$nextTick(() => {
          this.$refs.supplySearch.init(data);
        });
      },
      renewFormData(data) {
        this.dataForm.supplyId = data.id;
        this.dataForm.typeName = data.name;
      },
      //  打开查询部门弹窗
      openDeptDialog() {
        this.deptVisible = true
        this.$nextTick(() => {
          this.$refs.deptDialog.init()
        })
      },
      //  获取选择部门数据
      getDeptData(data) {
        this.dataForm.typeName = data[0].name
        this.dataForm.deptId = data[0].id
      },
      // 选择客户
      checkCustomer() {
        this.customerVisible = true;
        this.$nextTick(() => {
          this.$refs.customer.init();
        });
      },
      // 获取客户信息
      customerData(data) {
          this.dataForm.typeName = data.name
      },
      //凭证类型改变
      typeChange(){
        if(this.dataForm.billType==1){
          this.dataForm.twoType =1
        }else if(this.dataForm.billType==2){
          this.dataForm.twoType =7
        }else{
          this.dataForm.twoType = ''
        }
        this.dataForm.supplyId = ''
        this.dataForm.supplyName = ''
      },
      // 选择事件 得到选中的数据
      handleSelectionChange(data) {
        this.selectlistRow = data
      },
      addRow() {
        var timestamp = new Date().getTime()
        var list = {
          timestamp: timestamp,
          direct: '1',
          memo: '',
          subjectName: '',
          borrowMoney: '',
          loanMoney: ''
        };
        this.dataForm.detailList.push(list)
      },
      //  删除
      delData() {
        this.selectlistRow.forEach((item, index) => {
          for (let i = 0; i < this.dataForm.detailList.length; i++) {
            if (this.dataForm.detailList[i].timestamp === item.timestamp) {
              this.dataForm.detailList.splice(i, 1)
            }
          }
          this.selectlistRow = []
        })
      },
      checkParent(row){
        this.parentVisible = true
        this.$nextTick(() => {
          this.$refs.parentDialog.init(row.timestamp);
        });
      },
      getParentData(data){
        console.log(data)
        let subjectId = data.id
        let subjectName = ""+data.code + " " + data.name

        this.dataForm.detailList.forEach(item => {
          if(item.timestamp === data.timestamp){
            item.subjectName = subjectName
          }
        })
      },
    }
  }
</script>
